package com.lyxs916.testlibrary.rxjavatest.retrofittext;

import android.util.Log;

import com.lyxs916.common.HostType;
import com.lyxs916.network.BaseHttpRequest;
import com.lyxs916.network.HttpCallBack;
import com.lyxs916.testlibrary.rxjavatest.retrofittext.bean.TAliAddrsBean;
import com.lyxs916.testlibrary.rxjavatest.retrofittext.bean.TApiService;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017-06-05.
 */

public class TRetrofitTest {
    private final TApiService service;
    public String httpUrl = "http://gc.ditu.aliyun.com/";
    public static final int aa = 222666;

    public TRetrofitTest() {


        //每一个Call实例可以同步(call.excute())或者异步(call.enquene(CallBack<?> callBack))的被执行，
        //每一个实例仅仅能够被使用一次，但是可以通过clone()函数创建一个新的可用的实例。
        //默认情况下，Retrofit只能够反序列化Http体为OkHttp的ResponseBody类型
        //并且只能够接受ResponseBody类型的参数作为@body

        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(httpUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 使用RxJava作为回调适配器
                .addConverterFactory(GsonConverterFactory.create()) // 使用Gson作为数据转换器
                .build();

        service = retrofit.create(TApiService.class);
    }

    public void sendRequest() throws Exception {


        /**
         * 参数与Url里
         */
//        Call<AliAddrsBean> call = service.getIndexContent();

        /**
         * 带参数
         */
//        Call<AliAddrsBean> call = service.getIndexContentTow("苏州市","苏州市","苏州市");

        /**
         * map请求方式
         */
//        Map map = new HashMap();
//        map.put("a", "苏州市");
//        map.put("aa", "苏州市");
//        map.put("aaa", "苏州市");
//        map.put("uuuu", false);
//        Call<AliAddrsBean> call = service.getIndexContentThree(map);

        /**
         * 通过@Body注解指定一个对象作为Http请求的请求体（类似于一二三级城市的参数都放在的请求体indexRequestBean里面）
         */
//        IndexRequestBean indexRequestBean = new IndexRequestBean();
//        indexRequestBean.setA("上海市");
//        indexRequestBean.setAa("松江区");
//        indexRequestBean.setAaa("车墩镇");
//        Call<AliAddrsBean> call = service.getIndexContentFour(indexRequestBean);

        /**
         *@FormUrlEncoded 和@Field 发送表单数据
         */
//        Call<AliAddrsBean> call = service.getIndexContentFive("苏州市","苏州市","苏州市");

        /**
         *@Multipart和@Part 发送字节流数据
         */
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("utf-8"), "苏州市");//如果传值为null，则默认utf-8
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("utf-8"), "苏州市");
        RequestBody requestBody3 = RequestBody.create(MediaType.parse("utf-8"), "苏州市");
        RequestBody requestBody4 = RequestBody.create(MediaType.parse("utf-8"), new File("aaa"));//如果传值为null，则默认utf-8
//        Call<AliAddrsBean> call = service.getIndexContentSix(requestBody1,requestBody2,requestBody3);


        /**
         * 可以使用@Headers注解给函数设置静态的header
         */
//        Map map = new HashMap();
//        map.put("a", "苏州市");
//        map.put("aa", "苏州市");
//        map.put("aaa", "苏州市");
//        map.put("uuuu", false);
//        Call<AliAddrsBean> call = service.getIndexContentSeven(map);


        Map map = new HashMap();
        map.put("a", "苏州市");
        map.put("aa", "苏州市");
        map.put("aaa", "苏州市");
        map.put("uuuu", false);
        Call<TAliAddrsBean> call = service.getIndexContentNine("45613", map);

        /**
         * retrofit自带的回调
         */
        call.enqueue(new Callback<TAliAddrsBean>() {
            @Override
            public void onResponse(Call<TAliAddrsBean> call, Response<TAliAddrsBean> response) {
                Log.e("eeeeee", "");
            }

            @Override
            public void onFailure(Call<TAliAddrsBean> call, Throwable t) {
                t.printStackTrace();
                Log.e("eeeeee", "");
            }


        });


//        http://gc.ditu.aliyun.com/geocoding?a=上海市&aa=松江区&aaa=车墩镇


    }

    //Retrofit+Rxjava测试
    public void sendRequest2() throws Exception {
        /**
         *适配Rxjava
         */
        Observable<TAliAddrsBean> requestInde = service.getIndexContentEleven("北京市");
        requestInde.subscribeOn(Schedulers.newThread())//这里需要注意的是，网络请求在非ui线程。如果返回结果是依赖于Rxjava的，则需要变换线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<TAliAddrsBean>() {
                    @Override
                    public void call(TAliAddrsBean aliAddrsBean) {
                        //这里我只返回了成功的结果
                        System.out.println("完成");

                    }
                });
    }


    //Retrofit+Rxjava测试并发
    public void sendRequest3() throws Exception {

        Observable.zip(
                service.getIndexContentEleven("苏州市"),//第一个Observable对象
                service.getIndexContentEleven("上海市"),//第二个Observable对象
                new Func2<TAliAddrsBean, TAliAddrsBean, String>() {//function1中传入的是《1，第一个Observable对象；2，第二个Observable对象；3，返回类型》
                    @Override
                    public String call(TAliAddrsBean o, TAliAddrsBean o2) {
                        return o.getLat() + ":" + o2.getLat();
                    }
                })
                .subscribeOn(Schedulers.newThread())//这里需要注意的是，网络请求在非ui线程。如果返回结果是依赖于Rxjava的，则需要变换线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("test", "retrofit error " + e.getMessage());
                    }

                    @Override
                    public void onNext(String s) {//传入的是function1中返回的对象
                        Log.i("test", "retrofit结果1" + s);
                    }
                });
    }

    // path post
    public void sendRequest4() throws Exception {
        Map map = new HashMap();
        map.put("a", "商丘市");
        map.put("aa", "商丘市");
        map.put("aaa", "商丘市");
        map.put("uuuu", false);

        Observable<TAliAddrsBean> requestInde2 = service.executePost("geocoding", map);
        requestInde2.subscribeOn(Schedulers.newThread())//这里需要注意的是，网络请求在非ui线程。如果返回结果是依赖于Rxjava的，则需要变换线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<TAliAddrsBean>() {
                    @Override
                    public void call(TAliAddrsBean aliAddrsBean) {
                        //这里我只返回了成功的结果
                        System.out.println("完成");

                    }
                });

    }

    // path get
    public void sendRequest5() throws Exception {
        Map map = new HashMap();
        map.put("a", "商丘市");
        map.put("aa", "商丘市");
        map.put("aaa", "商丘市");
        map.put("AAAA", false);

        Observable<TAliAddrsBean> requestInde2 = service.executeGet("geocoding", map);
        requestInde2.subscribeOn(Schedulers.newThread())//这里需要注意的是，网络请求在非ui线程。如果返回结果是依赖于Rxjava的，则需要变换线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<TAliAddrsBean>() {
                    @Override
                    public void call(TAliAddrsBean aliAddrsBean) {
                        //这里我只返回了成功的结果
                        System.out.println("完成");

                    }
                });

    }


    public void sendRequest6() throws Exception {
        Map map = new HashMap();
        map.put("a", "北京市");
        map.put("aa", "北京市");
        map.put("aaa", "北京市");


        HttpCallBack.Builder buider = new HttpCallBack.Builder();

        HttpCallBack httpCallBack = new HttpCallBack<TAliAddrsBean>(buider) {
            @Override
            public void onSuccess(final TAliAddrsBean result) {
                super.onSuccess(result);
                if (result != null) {
                    return;
                }

            }
        };
        BaseHttpRequest.executePost(httpCallBack, "geocoding", map);
    }

    public void sendRequest7() throws Exception {
        /**
         *  @Header("Cache-Control") String cacheControl,
         @Path("type") String type,
         @Path("id") String id,
         @Path("startPage") int startPage);
         */
        Map map = new HashMap();
//        map.put("Cache-Control", "max-age=0");
//        map.put("type", "headline");
//        map.put("id", "T1348647909107");
//        map.put("startPage", "0");
//        map.put("-", "-20.html");


        HttpCallBack.Builder buider = new HttpCallBack.Builder();
        buider.setHostType(HostType.TYPE_THREE);

        HttpCallBack httpCallBack = new HttpCallBack<ResponseBody>(buider) {
            @Override
            public void onSuccess(final ResponseBody result) {
                super.onSuccess(result);
                if (result != null) {
                    return;
                }

            }
        };
//        for (int i = 0; i < 30; i++) {

            BaseHttpRequest.executeGet(httpCallBack, "nc/article/headline/T1348647909107/0-20.html");
//        }
    }
}
